/**
 * 标签页使用的store
 * tab = {
 *   title     $route.meta.title     标签页的标题
 *   name      component.name        标签组件的name，用于控制keep-live
 *   closable  $route.meta.closable  是否可关闭该标签页
 *   fullPath  $route.fullPath       路由
 *   cachable  $route.meta.cachable     是否需要缓存，用于控制keep-live
 * }
 */
// 路由定义
import routes from '@/router/routes'

const navTabs = {
  state: {
    openedTabs: []
  },
  mutations: {
    // 打开新的标签页
    openTab(state, tab) {
      if (!state.openedTabs.some(openedTab => openedTab.fullPath === tab.fullPath)) {
        // 不存在则push到openedTabs，用于生成标签
        state.openedTabs.push(tab)
      } else {
        // 存在时替换
        this.commit('replaceTab', {
          tab: {
            fullPath: tab.fullPath
          },
          newTab: tab
        })
      }
    },
    // 替换标签页
    replaceTab(state, { tab, newTab }) {
      let idx = state.openedTabs.findIndex(openedTab => openedTab.fullPath === tab.fullPath)
      state.openedTabs.splice(idx, 1, newTab)
    },
    // 关闭当前标签页
    closeTab(state, tab) {
      let idx = state.openedTabs.findIndex(openedTab => openedTab.fullPath === tab.fullPath)
      if (state.openedTabs[idx].closable !== false) {
        state.openedTabs.splice(idx, 1)
      }
    },
    // 关闭其他标签页，排除不可关闭的标签和当前标签
    closeOtherTabs(state, tab) {
      state.openedTabs = state.openedTabs.filter(openedTab => openedTab.closable === false || openedTab.fullPath === tab.fullPath)
    },
    // 关闭所有标签页，排除不可关闭的标签
    closeAllTabs(state) {
      state.openedTabs = state.openedTabs.filter(tab => tab.closable === false)
    }
  },
  getters: {
    // 用于keep-alive缓存判断，取所有可缓存标签的name属性
    openedTabsName: state => {
      return state.openedTabs.filter(tab => tab.cachable !== false).map(tab => tab.name)
    }
  }
}

// 递归获取所有不可关闭路由定义
function findAllNotClosableRoute(routeArr, parentPath) {
  let result = routeArr.filter(route => route.meta && route.meta.closable === false).map(route => {
    let name = route.meta.title || route.name
    return {
      title: name,
      closable: route.meta.closable,
      fullPath: filterPathString(parentPath, route.path),
      name: name,
      cachable: route.meta.cachable
    }
  })
  routeArr.filter(route => route.children).forEach(route => {
    result = result.concat(findAllNotClosableRoute(route.children, filterPathString(parentPath, route.path)))
  })
  return result
}

// 拼接path
function filterPathString(parentPath, path) {
  if (parentPath.lastIndexOf('/') === parentPath.length - 1) {
    parentPath = parentPath.substring(0, parentPath.length - 1)
  }
  if (path.indexOf('/') !== 0) {
    path = '/' + path
  }
  return parentPath + path
}

// 初始化不可关闭的标签页
navTabs.state.openedTabs = navTabs.state.openedTabs.concat(findAllNotClosableRoute(routes, ''))

export default navTabs
